﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Mail;

namespace TTServer
{
    public partial class FormChangeSystemEmail : Form
    {
        public FormChangeSystemEmail()
        {
            InitializeComponent();
        }

        private void FormChangeSystemEmail_Load(object sender, EventArgs e)
        {

        }

        private void btChangeSystemEmail_Click(object sender, EventArgs e)
        {
            String address = tbSystemEmailUsername.Text;
            String pass = tbSystemEmailPass.Text;
            bool isSendSuc = CheckSendMail(address, pass);
            if (isSendSuc)
            {
                Global.SetSystemEmail(address, pass);
                MessageBox.Show("Change system email successfully!", "Notify");
            }
            else
                MessageBox.Show("Your entered email does NOT exist. Please enter new one!", "Error");
        }

        private void btDefaultSystemEmail_Click(object sender, EventArgs e)
        {
            Global.SetSystemEmailToDefault();
            MessageBox.Show("System email has set to default system email!", "Notify");
            this.Close();
        }

        private bool CheckSendMail(String address, String pass)
        {
            var fromAddress = new MailAddress(address, "Admin");
                //var toAddress = new MailAddress("pf2707@yahoo.com.vn", "To Name");
            string fromPassword = pass;
            String subject = "Test changing system email";
            String body = "Do not reply this email";
            try
            {
                var smtp = new SmtpClient
                {
                    Host = "smtp.gmail.com",
                    Port = 587,
                    EnableSsl = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
                    Timeout = 20000
                };

                var toAddress = new MailAddress(Global.SystemEmailAddress, "N members System");
                //var toAddress = new MailAddress("pf2707@yahoo.com.vn", "N members System");

                using (var message = new MailMessage(fromAddress, toAddress)
                {
                    Subject = subject,
                    Body = body
                })
                {
                    smtp.Send(message);
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
